import datetime
import sys
sys.path.append("..")

import utils.raster as raster
import utils.common as common
import calendar
from dateutil import rrule
import os
import numpy as np

def monthly(start,end,vars = ["tp","t2m","wns","rh","fmc"]):
	start = datetime.datetime.strptime(start,"%Y%m")
	end = datetime.datetime.strptime(end,"%Y%m")
	months = rrule.rrule(rrule.MONTHLY,dtstart = start,until=end).count()
	days_delta = 0
	
	for month in range(months):
		monthrange = calendar.monthrange((start+datetime.timedelta(days = days_delta)).year, (start+datetime.timedelta(days = days_delta)).month)[1]
		month_data = {}
		data_info = {}

		for day in range(monthrange):
			for var in vars:
				if os.path.exists(os.path.join("/mnt/fire/Extract/",var,"%s_%s.tif"%(var,(start+datetime.timedelta(days = days_delta)).strftime("%Y%j")))):

					info,data = raster.open(os.path.join("/mnt/fire/Extract/",var,"%s_%s.tif"%(var,(start+datetime.timedelta(days = days_delta)).strftime("%Y%j"))))

					month_data.setdefault(var,[]).append(data)

					data_info.setdefault(var,info)

			days_delta += 1
		for var in vars:
			# print((start+datetime.timedelta(days = days_delta - monthrange)).strftime("%Y%m"))
			common.is_exists("/mnt/fire/monthly")
			if var is "tp":
				raster.save(os.path.join("/mnt/fire/monthly","%s_%s.tif"%(var,(start+datetime.timedelta(days = days_delta - monthrange)).strftime("%Y%m"))),np.sum(np.dstack(month_data[var]),axis = 2),data_info[var][0],data_info[var][1],data_info[var][2])
			else:
				raster.save(os.path.join("/mnt/fire/monthly","%s_%s.tif"%(var,(start+datetime.timedelta(days = days_delta - monthrange)).strftime("%Y%m"))),np.mean(np.dstack(month_data[var]),axis = 2),data_info[var][0],data_info[var][1],data_info[var][2])

def multi_year_mean(start,end,vars = ["tp","t2m","wns","rh","fmc"]):
	data_result = {}
	data_info = {}
	for month in range(1,13):
		for year in range(start,end+1):
			for var in vars:
				info, data = raster.open(os.path.join("/mnt/fire/monthly","%s_%d%02d.tif"%(var,year,month)))

				data_result.setdefault(var,[]).append(data)
				data_info.setdefault(var,info)


		for var in vars:
			raster.save(os.path.join("/mnt/fire/monthly","mul_%s_%02d.tif"%(var,month)),np.mean(np.dstack(data_result[var]),axis = 2),data_info[var][0],data_info[var][1],data_info[var][2])
			raster.save(os.path.join("/mnt/fire/monthly","std_%s_%02d.tif"%(var,month)),np.std(np.dstack(data_result[var]),axis = 2,ddof = 1),data_info[var][0],data_info[var][1],data_info[var][2])



if __name__ == '__main__':
	multi_year_mean(2013,2017)